package com.google.code.sms.android.service;

import java.io.File;

import com.google.code.sms.android.domain.MediaElement;
import com.google.code.sms.android.util.FileUtil;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

/**
 * @author Sindre Mehus
 */
public class MediaStoreService {

    private static final String TAG = MediaStoreService.class.getSimpleName();
    private static final Uri ALBUM_ART_URI = Uri.parse("content://media/external/audio/albumart");

    private final Context context;

    public MediaStoreService(Context context) {
        this.context = context;
    }

    public void saveInMediaStore(DownloadFile downloadFile) {
        MediaElement.Entry mediaElement = downloadFile.getMediaElement();
        File mediaElementFile = downloadFile.getCompleteFile();

        // Delete existing row in case the song has been downloaded before.
        deleteFromMediaStore(downloadFile);

        ContentResolver contentResolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.TITLE, mediaElement.getTitle());
        values.put(MediaStore.Audio.AudioColumns.ARTIST, mediaElement.getArtist());
        values.put(MediaStore.Audio.AudioColumns.ALBUM, mediaElement.getAlbum());
        values.put(MediaStore.Audio.AudioColumns.TRACK, mediaElement.getTrack());
        values.put(MediaStore.Audio.AudioColumns.YEAR, mediaElement.getYear());
        values.put(MediaStore.MediaColumns.DATA, mediaElementFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.MIME_TYPE, mediaElement.getContentType());
        values.put(MediaStore.Audio.AudioColumns.IS_MUSIC, 1);

        Uri uri = contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);

        // Look up album, and add cover art if found.
        Cursor cursor = contentResolver.query(uri, new String[]{MediaStore.Audio.AudioColumns.ALBUM_ID}, null, null, null);
        if (cursor.moveToFirst()) {
            int albumId = cursor.getInt(0);
            insertAlbumArt(albumId, downloadFile);
        }
        cursor.close();
    }

    public void deleteFromMediaStore(DownloadFile downloadFile) {
        ContentResolver contentResolver = context.getContentResolver();
        MediaElement.Entry song = downloadFile.getMediaElement();
        File file = downloadFile.getCompleteFile();

        int n = contentResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MediaStore.Audio.AudioColumns.TITLE_KEY + "=? AND " +
                        MediaStore.MediaColumns.DATA + "=?",
                new String[]{MediaStore.Audio.keyFor(song.getName()), file.getAbsolutePath()});
        if (n > 0) {
            Log.i(TAG, "Deleting media store row for " + song);
        }
    }

    private void insertAlbumArt(int albumId, DownloadFile downloadFile) {
        ContentResolver contentResolver = context.getContentResolver();

        Cursor cursor = contentResolver.query(Uri.withAppendedPath(ALBUM_ART_URI, String.valueOf(albumId)), null, null, null, null);
        if (!cursor.moveToFirst()) {

            // No album art found, add it.
            File albumArtFile = FileUtil.getAlbumArtFile(context, downloadFile.getMediaElement());
            if (albumArtFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId);
                values.put(MediaStore.MediaColumns.DATA, albumArtFile.getPath());
                contentResolver.insert(ALBUM_ART_URI, values);
                Log.i(TAG, "Added album art: " + albumArtFile);
            }
        }
        cursor.close();
    }

}